//
//  DrapWordPlayVC.swift
//  Game
//
//  Created by woniu on 2025/9/10.
//将单词卡片拖拽到空白占位卡片

import UIKit
import SnapKit

class DrapWordPlayVC: BaseVC {
    public var gameModel: GameModel!
    //图片
    private var imgCardItemList: [DrapWordItem] = []
    //单词
    private var wordItemList: [DrapWordItem] = []

    private let leftTable = UITableView(frame: .zero, style: .plain)
    private let rightTable = UITableView(frame: .zero, style: .plain)
    private var placeholders: [String?] = []
    // drag state
    private var draggingSnapshot: UIView?
    private var draggingSourceIndexPath: IndexPath?
    private var draggingWordIndex: Int?
    private var originalSnapshotCenter: CGPoint = .zero
    private let wordCardSizeW:CGFloat = 150

    private let resetBtn = UIButton(type: .system)
    private let checkBtn = UIButton(type: .system)

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        
        createDataSource()
        setupTables()
        setupBottomButtons()
    }
    
    private func createDataSource(){
        wordItemList.removeAll()
        imgCardItemList.removeAll()
        if let gm = gameModel {
            for wordItem in gm.words{
                let item  = DrapWordItem()
                item.imgName = wordItem.imgName
                item.word = wordItem.word
                wordItemList.append(item)
            }
            for wordItem in gm.words{
                let item  = DrapWordItem()
                item.imgName = wordItem.imgName
                item.word = wordItem.word
                imgCardItemList.append(item)
            }
        }
        if wordItemList.isEmpty { wordItemList = [] }
        if imgCardItemList.isEmpty { imgCardItemList = [] }
        placeholders = Array(repeating: nil, count: wordItemList.count)
    }

    private func setupTables() {
        leftTable.register(DrapLeftCell.self, forCellReuseIdentifier: "DrapLeftCell")
        leftTable.dataSource = self
        leftTable.delegate = self
        leftTable.backgroundColor = .clear
        leftTable.separatorStyle = .none
        view.addSubview(leftTable)

        rightTable.register(UITableViewCell.self, forCellReuseIdentifier: "RightCell")
        rightTable.dataSource = self
        rightTable.delegate = self
        rightTable.backgroundColor = .clear
        rightTable.separatorStyle = .none
        view.addSubview(rightTable)

        let guide = view.safeAreaLayoutGuide
        leftTable.snp.makeConstraints { make in
            make.left.bottom.equalToSuperview()
            make.top.equalTo(backButton.snp.bottom)
            make.width.equalTo(guide.snp.width).multipliedBy(0.65)
        }
        rightTable.snp.makeConstraints { make in
            make.right.equalTo(guide.snp.right).offset(-12)
            make.top.equalTo(leftTable.snp.top)
            make.bottom.equalTo(leftTable.snp.bottom)
            make.left.equalTo(leftTable.snp.right).offset(10)
        }

        let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        pan.delegate = self
        rightTable.addGestureRecognizer(pan)
    }

    private func cardHeightForLayout() -> CGFloat {
        let count = wordItemList.count >= 10 ? 10 : (wordItemList.count <= 6 ? 6 : wordItemList.count)
        let h = view.bounds.height
        return h / CGFloat(count)
    }

    private func setupBottomButtons() {
        resetBtn.setTitle("Reset", for: .normal)
        resetBtn.setTitleColor(.white, for: .normal)
        resetBtn.backgroundColor = UIColor(white: 0.15, alpha: 1)
        resetBtn.layer.cornerRadius = 8
        resetBtn.addTarget(self, action: #selector(onResetTapped), for: .touchUpInside)
        view.addSubview(resetBtn)

        checkBtn.setTitle("Check", for: .normal)
        checkBtn.setTitleColor(.white, for: .normal)
        checkBtn.backgroundColor = UIColor(white: 0.15, alpha: 1)
        checkBtn.layer.cornerRadius = 8
        checkBtn.addTarget(self, action: #selector(onCheckTapped), for: .touchUpInside)
        view.addSubview(checkBtn)

        checkBtn.snp.makeConstraints { make in
            make.centerX.equalTo(view.snp.centerX).offset(80)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-20)
            make.width.equalTo(120)
            make.height.equalTo(48)
        }
        resetBtn.snp.makeConstraints { make in
            make.centerY.equalTo(checkBtn.snp.centerY)
            make.centerX.equalTo(view.snp.centerX).offset(-80)
            make.width.equalTo(120)
            make.height.equalTo(48)
        }
    }

    @objc private func onResetTapped() {
        createDataSource()
        wordItemList.shuffle()
        imgCardItemList.shuffle()
        leftTable.reloadData()
        rightTable.reloadData()
    }

    @objc private func onCheckTapped() {
        for item in wordItemList{item.isShowResult = true}
        for item in imgCardItemList{item.isShowResult = true}
        leftTable.reloadData()
    }

    // MARK: - Drag
    @objc private func handlePan(_ g: UIPanGestureRecognizer) {
        switch g.state {
        case .began:
            draggingSnapshot?.removeFromSuperview()
            draggingSnapshot = nil
            guard let idxPath = rightTable.indexPathForRow(at: g.location(in: rightTable)) else { return }
            //被拖动过的
            if wordItemList[idxPath.row].word.isEmpty{
                return
            }
            guard let cell = rightTable.cellForRow(at: idxPath) else { return }
            draggingSourceIndexPath = idxPath
            draggingWordIndex = idxPath.row
            let snapshot = snapshotOfCell(cell)
            snapshot.center = cell.convert(cell.contentView.center, to: view.window)
            view.window?.addSubview(snapshot)
            draggingSnapshot = snapshot
            originalSnapshotCenter = snapshot.center
            snapshot.transform = CGAffineTransform(scaleX: 1.05, y: 1.05)
            snapshot.alpha = 0.98
        case .changed:
            guard let snapshot = draggingSnapshot else { return }
            let translation = g.translation(in: view.window)
            snapshot.center = CGPoint(x: snapshot.center.x + translation.x, y: snapshot.center.y + translation.y)
            g.setTranslation(.zero, in: view.window)
            detectHighlightForSnapshot(snapshot)
        case .ended, .cancelled, .failed:
            guard let snapshot = draggingSnapshot, let wordIndex = draggingWordIndex else { cleanupDrag(); return }
            if let targetIndex = indexOfPlaceholderContaining(point: snapshot.center) {
                // place word into placeholder
                placeholders[targetIndex] = wordItemList[wordIndex].word
                // right side card becomes empty placeholder: remove word
                wordItemList[wordIndex].word = ""
                leftTable.reloadRows(at: [IndexPath(row: targetIndex, section: 0)], with: .none)
                rightTable.reloadRows(at: [IndexPath(row: wordIndex, section: 0)], with: .none)
                UIView.animate(withDuration: 0.25, animations: {
                    snapshot.alpha = 0.0
                }, completion: { _ in snapshot.removeFromSuperview() })
            } else {
                // animate back
                UIView.animate(withDuration: 0.36, animations: {
                    snapshot.center = self.originalSnapshotCenter
                    snapshot.transform = .identity
                }, completion: { _ in snapshot.removeFromSuperview() })
            }
            cleanupDrag()
        default: break
        }
    }

    private func cleanupDrag() {
        for i in 0..<wordItemList.count {
            if let cell = leftTable.cellForRow(at: IndexPath(row: i, section: 0)), let ph = cell.contentView.subviews.first(where: { $0 is PlaceholderCardView }) as? PlaceholderCardView {
                ph.setHighlighted(false)
            }
        }
        draggingSnapshot?.removeFromSuperview()
        draggingSnapshot = nil
        draggingSourceIndexPath = nil
        draggingWordIndex = nil
    }

    private func snapshotOfCell(_ cell: UITableViewCell) -> UIView {
        let frameInWindow = cell.convert(cell.contentView.frame, to: view.window)
        let snapshot = UIView(frame: frameInWindow.insetBy(dx: 6, dy: 6))
        snapshot.size = CGSizeMake(wordCardSizeW, cell.contentView.height-20)//20上下间距
        snapshot.backgroundColor = UIColor(white: 0.18, alpha: 1)
        snapshot.layer.cornerRadius = 8
        snapshot.layer.shadowColor = UIColor.black.cgColor
        snapshot.layer.shadowOpacity = 0.25
        snapshot.layer.shadowRadius = 6
        snapshot.layer.shadowOffset = CGSize(width: 0, height: 3)
        let label = UILabel(frame:snapshot.bounds)
        if let contentLabel = cell.contentView.subviews.first(where: { $0 is DrapWordCardView }) as? DrapWordCardView {
            label.text = contentLabel.label.text
        }
        label.font = UIFont.systemFont(ofSize: 18, weight: .bold)
        label.textAlignment = .center
        label.textColor = .white
        snapshot.addSubview(label)
        return snapshot
    }

    private func detectHighlightForSnapshot(_ snapshot: UIView) {
        let center = snapshot.center
        for i in 0..<wordItemList.count {
            let idx = IndexPath(row: i, section: 0)
            
            if let cell = leftTable.cellForRow(at: idx){
                for suView in cell.contentView.subviews.first?.subviews ?? []{
                    if let ph = suView as?  PlaceholderCardView{
                        let rect = ph.convert(ph.bounds, to: view.window)
                        if rect.contains(center) {
                            ph.setHighlighted(true)
                        } else {
                            ph.setHighlighted(false)
                        }
                    }
                }
            }
        }
    }

    private func indexOfPlaceholderContaining(point: CGPoint) -> Int? {
        for i in 0..<wordItemList.count {
            let idx = IndexPath(row: i, section: 0)
            if let cell = leftTable.cellForRow(at: idx){
                for suView in cell.contentView.subviews.first?.subviews ?? []{
                    if let ph = suView as?  PlaceholderCardView{
                        let rect = ph.convert(ph.bounds, to: view.window)
                        if rect.contains(point) { return i }
                    }
                }
            }
        }
        return nil
    }

}

extension DrapWordPlayVC: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true }
}

extension DrapWordPlayVC: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return wordItemList.count }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return cardHeightForLayout()
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView == leftTable {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "DrapLeftCell", for: indexPath) as! DrapLeftCell
            let item = imgCardItemList[indexPath.row]
            cell.update(item: item,userSelecteWord: placeholders[indexPath.row],index: indexPath.row)
            cell.onCheckFinishBlock = {[weak self]in
                guard let `self` = self else { return }
                //检查完成最后一个
                if indexPath.row == imgCardItemList.count-1{
                    let isAllTrue = self.imgCardItemList.allSatisfy { wItem in
                        return wItem.isAnswerCorrect == true
                    }
                    //全部正确，绽放烟花
                    if isAllTrue{
                        FireworksHelper.shared.showRocketAndFireworks(in: self.view, showSuccess: true)
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.7) {
                            FireworksHelper.shared.showRocketAndFireworks(in: self.view, showSuccess: true)
                        }
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1.5) {
                            FireworksHelper.shared.showRocketAndFireworks(in: self.view, showSuccess: false)
                        }
                    }
                    
                }
               
            }
            return cell
            
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "RightCell", for: indexPath)
            cell.backgroundColor = .clear
            cell.selectionStyle = .none
            cell.contentView.subviews.forEach { $0.removeFromSuperview() }
            let card = DrapWordCardView()
            cell.contentView.addSubview(card)
            card.snp.makeConstraints {make in
                make.centerX.equalToSuperview()
                make.width.equalTo(wordCardSizeW)
                make.top.equalToSuperview().offset(10)
                make.bottom.equalToSuperview().offset(-10)
            }
            let item = wordItemList[indexPath.row]
            card.label.text = item.word
            if item.word.isEmpty {
                card.label.text = ""; card.backgroundColor = UIColor(white: 0.12, alpha: 1)
            }
            return cell
        }
    }
}

